package com.vpen.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/26 20:56
 */
@Slf4j
public class StompClientApp {

    public static final String URL = "ws://localhost:8000/chat-endpoint";


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建客户端
        StandardWebSocketClient client = new StandardWebSocketClient();

        WebSocketStompClient socketStompClient = new WebSocketStompClient(client);
        ListenableFuture<StompSession> future = socketStompClient.connect(URL, new StompSessionHandlerAdapter() {
            @Override
            public Type getPayloadType(StompHeaders headers) {
                return super.getPayloadType(headers);
            }
        });

        future.addCallback(new ListenableFutureCallback<StompSession>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("连接失败");
            }

            @Override
            public void onSuccess(StompSession result) {
                log.debug("连接成功");
            }
        });


        StompSession stompSession = future.get();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            stompSession.send("/app/hello2", str.getBytes(StandardCharsets.UTF_8));
        }
    }
}
